package com.ifpe.ifmoodledroid.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;

import com.ifpe.ifmoodledroid.R;
import com.ifpe.ifmoodledroid.db.DBHelper;
import com.ifpe.ifmoodledroid.db.RepositorioUsuario;
import com.ifpe.ifmoodledroid.model.Usuario;
import com.ifpe.ifmoodledroid.model.UsuarioAdapter;

public class TelaLoginActivity extends Activity {

	private final String IP_SERVICE = "192.168.254.1", PORTA_SERVICE = "8081";
	private final String URL_VERIFICA_USUARIO = "http://" + IP_SERVICE + ":"
			+ PORTA_SERVICE + "/IFMoodleDroidServices/rest/verificarPost/";
	private ImageView imgLogo;
	private EditText editTextLogin, editTextSenha;
	private List<Usuario> usuariosSalvos = null;
	private String login, senha;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		RepositorioUsuario repositorioUsuario = new RepositorioUsuario(
				new DBHelper(TelaLoginActivity.this));
		usuariosSalvos = repositorioUsuario.getUsuarios();

		if (usuariosSalvos != null && usuariosSalvos.size() > 0) {
			carregaTelaLoginSalvo();

		} else {
			carregaTelaLoginPrincipal();
		}
	}
	
	private void carregaTelaLoginPrincipal(){
		setContentView(R.layout.tela_login);
		editTextLogin = (EditText) findViewById(R.id.editText1);
		editTextSenha = (EditText) findViewById(R.id.editText2);
		imgLogo = (ImageView) findViewById(R.id.imgLogo);

		try {
			InputStream inputStream = getAssets().open("moodlelogo.gif");
			Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
			//imgLogo.setImageBitmap(bitmap);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void carregaTelaLoginSalvo(){
		setContentView(R.layout.tela_logins_salvos);
		// ((TextView)findViewById(R.id.textView1)).setText(Integer.toString(usuariosSalvos.size()));
		ListView listLogin = (ListView) findViewById(R.id.listView1);
		UsuarioAdapter adapter = new UsuarioAdapter(this, usuariosSalvos);
		listLogin.setAdapter(adapter);

		listLogin.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> lista, View v,
					int position, long id) {
				// TODO Auto-generated method stub
				Usuario usuario = (Usuario) lista
						.getItemAtPosition(position);
				login = usuario.getLogin();
				senha = usuario.getSenha();

				logarUsuarioSalvo();
			}
		});
	}

	// -------------------------

	// -------------------------
	public void entrarClick(View v) {
		String login = editTextLogin.getText().toString();
		String senha = editTextSenha.getText().toString();
		int flagSalvar = 0;
		CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);

		if (checkBox.isChecked()) {
			flagSalvar = 1;
		}

		if (login == null || login.equals("") || senha == null
				|| senha.equals("")) {
			Toast.makeText(this, "Por favor, digite seus dados de acesso.",
					Toast.LENGTH_SHORT).show();
		} else {
			new DownloadJsonAsyncTask().execute(URL_VERIFICA_USUARIO, login, senha,
					Integer.toString(flagSalvar));
		}

	}

	public void logarUsuarioSalvo() {
		String flagSalvar = "2";
		new DownloadJsonAsyncTask().execute(URL_VERIFICA_USUARIO, login,
				senha, flagSalvar);
	}

	public void sairClick(View v) {
		finish();
	}

	public void outroUsuario(View v) {

		carregaTelaLoginPrincipal();
		Button botaoVoltar = (Button) findViewById(R.id.voltar_button);
		botaoVoltar.setVisibility(1);
		
	}
	
	public void voltarTela(View v){
		carregaTelaLoginSalvo();
	}

	class DownloadJsonAsyncTask extends AsyncTask<String, Void, JSONObject> {

		private ProgressDialog dialog;
		
		
		String flagSalvar = "";

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = ProgressDialog.show(TelaLoginActivity.this, "Aguarde",
					"Fazendo login...");
		}

		@Override
		protected JSONObject doInBackground(String... params) {

			login = params[1];
			senha = params[2];
			flagSalvar = params[3];
			String result = getRESTFileContent(params[0], login, senha, flagSalvar);
			

			Log.i("URL URL URL URL URL", params[0]);

			JSONObject jsonObject = null;

			if (result == null) {
				Log.e("LogandoIFMoodleDroid", "Falha ao acessar WS");
				return null;
			} else {
				Log.i("Result Retornado", result);
			}

			try {
				jsonObject = new JSONObject(result);

			} catch (Exception e) {
				// TODO: handle exception
			}
			return jsonObject;
		}

		protected void onPostExecute(JSONObject result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();

			if (result != null) {

				Intent intent = new Intent(TelaLoginActivity.this,
						TelaPrincipalActivity.class);
				Usuario usuario = new Usuario();
				try {
					usuario.setNome(result.getString("nome"));
					usuario.setSobrenome(result.getString("sobrenome"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				intent.putExtra("usuario", usuario);

				if (Integer.parseInt(flagSalvar) == 1) {
					Log.i("HORA DE SALVAR NO BANCO", "SALVAR");
					Usuario usuario2 = null;
					try {
						usuario2 = new Usuario(result.getString("login"),
								result.getString("senha"),
								result.getString("nome"),
								result.getString("sobrenome"));
						Log.i("SALVANDO NO BANCO", usuario2.getNome() + " "
								+ usuario2.getSobrenome());
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					RepositorioUsuario repositorioUsuario = new RepositorioUsuario(
							new DBHelper(TelaLoginActivity.this));
					repositorioUsuario.inserir(usuario2);
				} else if (flagSalvar.equals("2")) {
					Usuario usuario2 = null;
					try {
						usuario2 = new Usuario(result.getString("login"),
								result.getString("senha"),
								result.getString("nome"),
								result.getString("sobrenome"));
						Log.i("SALVANDO NO BANCO", usuario2.getNome() + " "
								+ usuario2.getSobrenome());
					} catch (JSONException e) {

						e.printStackTrace();
					}
					RepositorioUsuario repositorioUsuario = new RepositorioUsuario(
							new DBHelper(TelaLoginActivity.this));
					repositorioUsuario.atualizar(usuario2);
				}

				startActivity(intent);
			} else {

				Toast.makeText(TelaLoginActivity.this,
						"Dados de acesso incorretos.", Toast.LENGTH_SHORT)
						.show();
			}
		}

		private String toString(InputStream is) throws IOException {

			byte[] bytes = new byte[1024];
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int lidos;
			while ((lidos = is.read(bytes)) > 0) {
				baos.write(bytes, 0, lidos);
			}
			return new String(baos.toByteArray());
		}

		public String getRESTFileContent(String url, String loginUsuario, String senhaUsuario, String flagSalvar) {
			HttpClient httpclient = new DefaultHttpClient();
			
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
			nameValuePairs.add(new BasicNameValuePair("login", loginUsuario));
			nameValuePairs.add(new BasicNameValuePair("senha", senhaUsuario));
			nameValuePairs.add(new BasicNameValuePair("flagEncriptacao", flagSalvar));

			try {
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httpPost);

				HttpEntity entity = response.getEntity();

				if (entity != null) {
					InputStream instream = entity.getContent();
					String result = toString(instream);

					instream.close();
					return result;
				}
			} catch (Exception e) {
				Log.e("IFMoodleDROID", "Falha ao acessar Web service", e);
			}
			return null;
		}

	}
}
